package com.lovo.invoicing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.invoicing.bean.PageBean;
import com.lovo.invoicing.bean.ProviderBean;
import com.lovo.invoicing.mapper.ProviderMapper;
import com.lovo.invoicing.service.IProviderService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 供应商服务层
 */
@Service
public class ProviderServiceImpl extends ServiceImpl<ProviderMapper, ProviderBean> implements IProviderService {
   @Autowired
   ProviderMapper providerMapper;

    private static final String XLS = "xls";
    /**
     * 定义全局的常量值
     */
    private static final String XLSX = "xlsx";

    private Logger logger = LoggerFactory.getLogger(ProviderServiceImpl.class);

    //添加供应商
    @Override
    @Transactional
    public void addProvider(ProviderBean providerBean) {
        baseMapper.insert(providerBean);
    }
   //根据id查找供应商
    @Override
    public ProviderBean queryProviderById(int providerId) {
        return baseMapper.selectById(providerId);
    }
   //修改供应商
    @Override
    @Transactional
    public void updateProvider(ProviderBean providerBean) {
        baseMapper.updateById(providerBean);
    }

    @Override
    public IPage<ProviderBean> queryProvidersByPage(PageBean<ProviderBean> pageBean) {
        QueryWrapper<ProviderBean> qw = new QueryWrapper<>();
        ProviderBean p = pageBean.getT();
        if (p.getProviderName()!=null && !"".equals(p.getProviderName())){
            qw.like("provider_name",p.getProviderName());
        }
        if (p.getProviderScope()!=null && !"".equals(p.getProviderScope())){
            qw.like("provider_scope",p.getProviderScope());
        }
        return baseMapper.selectPage(new Page<>(pageBean.getPageNo(), pageBean.getPageSize()),qw);
    }

    @Override
    public List<ProviderBean> queryAllProviders() {
        return baseMapper.selectList(null);
    }

    @Override
    public void importProviderList(List<ProviderBean> providerBeanList) {

    }

    @Override
    public Map<String, Object> importExcel(MultipartFile file) {
        List<ProviderBean> tblFixChangeList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        Workbook workbook = null;

        String filename = file.getOriginalFilename();
        try {
            if (filename != null) {
                if (filename.endsWith(XLS)) {
                    // 2003
                    workbook = new HSSFWorkbook(file.getInputStream());
                } else if (filename.endsWith(XLSX)) {
                    // 2007
                    workbook = new XSSFWorkbook(file.getInputStream());
                } else {
                    throw new Exception("文件不是Excel文件");
                }
            } else {
                logger.error("文件为空");
            }
            // 获取sheet
            Sheet sheet = workbook.getSheet("Sheet1");

            int lastRowNum = sheet.getLastRowNum();
            if (lastRowNum == 0) {
                throw new Exception("请填写行数");
            }

            for (int i = 1; i < lastRowNum + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    // 读取cell单元格内容
                    ProviderBean tblFixChange = new ProviderBean();
                    // 供应商
                    String providerName = getCellValue(row.getCell(0));
                    tblFixChange.setProviderName(providerName);
                    // 负责人
                    String providerLeader = getCellValue(row.getCell(1));
                    tblFixChange.setProviderLeader(providerLeader);
                    //电话号码
                    Cell cell = row.getCell(2);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    String phoneNumber = getCellValue(cell);
                    tblFixChange.setPhoneNumber(phoneNumber);
                    // 供应商地址
                    String providerAddress = getCellValue(row.getCell(3));
                    tblFixChange.setProviderAddress(providerAddress);
                    //经营范围
                    String providerScope= getCellValue(row.getCell(4));
                    tblFixChange.setProviderScope(providerScope);
                    tblFixChangeList.add(tblFixChange);
                }
            }
            // 批量插入
            providerMapper.addBatchMembers(tblFixChangeList);
            map.put("status", 1);
            map.put("data", "导入数据成功");
        } catch (Exception e) {
            map.put("status", -1);
            map.put("data", "导入数据异常");
            logger.error(e.getMessage(), e);
        }
        return map;
    }

    private String getCellValue(Cell cell) {
        // 单元格内容
        String value = "";
        if (cell != null) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                // 数字
                case HSSFCell
                        .CELL_TYPE_NUMERIC:
                    value = cell.getNumericCellValue() + "";
                    break;
                // 字符串
                case HSSFCell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue();
                    break;
                // Boolean
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    value = cell.getBooleanCellValue() + "";
                    break;
                // 公式
                case HSSFCell.CELL_TYPE_FORMULA:
                    value = cell.getCellFormula() + "";
                    break;
                // 空格
                case HSSFCell.CELL_TYPE_BLANK:
                    value = "";
                    break;
                // 错误
                case HSSFCell.CELL_TYPE_ERROR:
                    value = "非法字符";
                default:
                    value = "未知类型";
                    break;
            }
        }
        return value.trim();
    }

}
